package com.amikomgamedev.panjatpinang.states;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.camera.hud.HUD;
import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.FillResolutionPolicy;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.text.Text;
import org.andengine.entity.util.FPSLogger;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.font.Font;
import org.andengine.opengl.font.FontFactory;
import org.andengine.opengl.texture.ITexture;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.view.RenderSurfaceView;
import org.andengine.ui.activity.SimpleBaseGameActivity;
import org.andengine.util.color.Color;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnShowListener;
import android.content.Intent;
import android.text.InputType;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;

import com.amikomgamedev.panjatpinang.CoolDownButton;
import com.amikomgamedev.panjatpinang.Data;
import com.amikomgamedev.panjatpinang.Define;
import com.amikomgamedev.panjatpinang.Game;
import com.amikomgamedev.panjatpinang.Loading;
import com.amikomgamedev.panjatpinang.Utils;
import com.amikomgamedev.panjatpinang.database.ScoreDbHelper;
import com.amikomgamedev.panjatpinang.database.ScoreSVC;
import com.amikomgamedev.panjatpinang.entities.Entity_BendaJatuh;
import com.amikomgamedev.panjatpinang.entities.Entity_Mc;

import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.google.ads.AdRequest.ErrorCode;
import com.heyzap.sdk.HeyzapLib;

/*
 * AndEngineGamePanjatPinang
 * State_GamePlay.java
 * Pratama Wijaya
 * set.mnemonix@gmail.com
 * 7:23:44 PM , Jul 14, 2012
 */

public class State_GamePlay extends SimpleBaseGameActivity implements Define,
		Data, IUpdateHandler, IOnSceneTouchListener {

	// daftar state
	private static final int	STATE_GAMEPLAY_LOADING	= 0;
	private static final int	STATE_GAMEPLAY_INGAME	= 1;
	private static final int	STATE_GAMEPLAY_MENU		= 2;
	private static final int	STATE_GAMEPLAY_GAMEOVER	= 3;

	private int					StateCurrent			= STATE_GAMEPLAY_LOADING;

	private Camera				mCamera;
	private Scene				Scene_Gameplay;
	private Entity_Mc			mcR;
	private Entity_BendaJatuh	entityBJ;
	private HUD					HudMainHud, endHud;
	private Context				context;

	public State_GamePlay		_instance;

	private float				second					= 0;
	private float				score					= 0;

	private Text				time, txtSubmit, scoreNya, txtScore,
			txtHighScore, highScore;
	private boolean				counter					= false;

	private ITexture			texFont, texFontSubmit;
	private Font				font, fontSubmit;

	private static int			timerCountdown			= 10;

	private String				mValue;

	private ScoreDbHelper		scoreDb;
	private ScoreSVC			scoreSvc;

	private float				getRctXPos;
	private AdView 				adview;
	private final String 		MY_AD = "a15210c0eadc179";
	
	@Override
	public EngineOptions onCreateEngineOptions() {
		// TODO Auto-generated method stub
		Utils.TRACE("masuk ke onCreateEngine");
		_instance = this;
		mCamera = new Camera(0, 0, GAME_SCREEN_WIDTH, GAME_SCREEN_HEIGHT);
		EngineOptions en = new EngineOptions(true,
				ScreenOrientation.PORTRAIT_FIXED, new FillResolutionPolicy(), mCamera);
		en.getAudioOptions().setNeedsMusic(true);

		// load heyZap
		HeyzapLib.load(this);
		return en;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		HeyzapLib.onActivityResult(requestCode, resultCode, data);
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void onCheckinClicked(float score) {
		HeyzapLib.checkin(this,
				"Yes I Got " + String.format("%.02f", score)
						+ "seconds, Can U Beat My Highscore?");
	}

	@Override
	protected void onCreateResources() {
		// TODO Auto-generated method stub
		// mau load apa dulu
		Utils.TRACE("StateGame : onCreateResources");
		Game.setContext(this);
		context = this;
		texFontSubmit = new BitmapTextureAtlas(this.getTextureManager(), 256,
				256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);

		texFont = new BitmapTextureAtlas(this.getTextureManager(),
				FNT_TEX_WIDTH, FNT_TEX_HEIGHT, TextureOptions.BILINEAR);
		font = FontFactory.createFromAsset(this.getFontManager(), texFont,
				this.getAssets(), FONT_STYLE, 16, true,
				android.graphics.Color.BLACK);
		fontSubmit = FontFactory.create(this.getFontManager(), texFontSubmit,
				16, android.graphics.Color.WHITE);

		font.load();
		fontSubmit.load();

		scoreSvc = new ScoreSVC();

		scoreDb = new ScoreDbHelper(this);
		scoreDb.CreateTable();

	}

	@Override
	protected Scene onCreateScene() {
		// TODO Auto-generated method stub
		mEngine.registerUpdateHandler(new FPSLogger());
		mEngine.registerUpdateHandler(this);

		Scene_Gameplay = new Scene();
		Scene_Gameplay.attachChild(new Scene());
		Scene_Gameplay.setOnSceneTouchListener(this);
		Scene_Gameplay.setTouchAreaBindingOnActionDownEnabled(true);
		Scene_Gameplay.setColor(Color.WHITE);

		Game.loadBgLoading();

		switchState(STATE_GAMEPLAY_LOADING);

		return Scene_Gameplay;
	}

	@Override
	public void onUpdate(float pSecondsElapsed) {
		// TODO Auto-generated method stub
		switch (StateCurrent) {
			case STATE_GAMEPLAY_LOADING:
				// Utils.TRACE("Gameplay : onUpdate STATE_GAMEPLAY LOADING");
				if (Loading.isLoadingActive())
					Loading.updateLoading();
				else {
					entityBJ = new Entity_BendaJatuh(Game.sprEmber,
							Game.sprKerdus, Game.sprMagicjar, Game.sprPayung,
							Game.sprTas, this);

					entityBJ.getSprEmber().setPosition(-300, -300);
					switchState(STATE_GAMEPLAY_INGAME);
				}
				break;
			case STATE_GAMEPLAY_INGAME:
				// Utils.TRACE("Gameplay : onUpdate STATE_GAMEPLAY INGAME");
				mcR.mcUpdate();

				if (counter) {
					// milisecond += 1;
					// if (milisecond > 99) {
					// second += 1;
					// score += 1;
					// milisecond = 0;
					// if (second > 59) {
					// minute += 1;
					// second = 0;
					// }
					// }

					second += pSecondsElapsed;
					score += pSecondsElapsed;

					time.setText((int) (second / 60) + ":"
							+ (int) (second % 60));
					Utils.TRACE("time asli: : " + second);
					Utils.TRACE("time pake mili : " + (int) (second / 60) + ":"
							+ (int) (second % 60));

				}
				if (timerCountdown == 0) {
					entityBJ.setBendaJatuh();
					timerCountdown = Utils.getRandomValue(40);
					timerCountdown += 0;
				}

				// entityBJ.getSprEmber().setVisible(true);
				// entityBJ.getSprMagicJar().setVisible(true);

				if (!entityBJ.isOnScreen()
						&& mcR.getCurrentState() == MC_STATE_NAIK)
					timerCountdown--;
				entityBJ.bjUpdate();
				float entCurPosEmber = entityBJ.getSprEmber().getY();
				if (entCurPosEmber >= Define.GAME_SCREEN_HEIGHT) {
					entityBJ.getSprEmber().setVisible(true);
				}
				float entCurPosMJ = entityBJ.getSprMagicJar().getY();
				if (entCurPosMJ >= Define.GAME_SCREEN_HEIGHT) {
					entityBJ.getSprMagicJar().setVisible(true);

				}
				float entCurPosKerdus = entityBJ.getSprKerdus().getY();
				if (entCurPosKerdus >= Define.GAME_SCREEN_HEIGHT) {

					entityBJ.getSprKerdus().setVisible(true);
				}
				float entCurPosPayung = entityBJ.getSprPayung().getY();
				if (entCurPosPayung >= Define.GAME_SCREEN_HEIGHT) {
					entityBJ.getSprPayung().setVisible(true);
				}
				float entCurPosTas = entityBJ.getSprTas().getY();
				if (entCurPosTas >= Define.GAME_SCREEN_HEIGHT) {
					entityBJ.getSprTas().setVisible(true);
				}

				if (mcR.getRctMc().collidesWith(entityBJ.getRctEmber())) {
					Game.mscSoundKejatuhan.play();
					mcR.isSwap = false;
					mcR.setAnim(SPR_ANIME_SAKIT, 1);
					float x = Game.SprIndikatorPoint.getX();
					float y = Game.SprIndikatorPoint.getY();
					if (y <= Game.SprIndikatorGaris.getY() - 8
							+ Game.SprIndikatorGaris.getHeight()) {
						Game.SprIndikatorPoint.setPosition(x, y
								+ PENURUNAN_PIXEL_MEDIUM);

					} else {
						y = Game.SprIndikatorGaris.getY() - 8
								+ Game.SprIndikatorGaris.getHeight();

					}
					float yMap = Game.SprImgGameplayBackground.getY();
					if (yMap >= 0 - (Game.SprImgGameplayBackground.getHeight() - GAME_SCREEN_HEIGHT)) {
						Game.SprImgGameplayBackground.setPosition(0, yMap
								- PENURUNAN_MAP_MEDIUM);
					} else {
						yMap = 0 - (Game.SprImgGameplayBackground.getHeight() - GAME_SCREEN_HEIGHT);
					}
					entityBJ.getSprEmber().setVisible(false);

				}
				if (mcR.getRctMc().collidesWith(entityBJ.getRctMagicJar())) {
					Game.mscSoundKejatuhan.play();
					mcR.setAnim(SPR_ANIME_SAKIT, 1);
					float x = Game.SprIndikatorPoint.getX();
					float y = Game.SprIndikatorPoint.getY();
					if (y <= Game.SprIndikatorGaris.getY() - 8
							+ Game.SprIndikatorGaris.getHeight()) {
						Game.SprIndikatorPoint.setPosition(x, y
								+ PENURUNAN_PIXEL_HIGH);
					} else {
						y = Game.SprIndikatorGaris.getY() - 8
								+ Game.SprIndikatorGaris.getHeight();
					}
					float yMap = Game.SprImgGameplayBackground.getY();
					if (yMap >= 0 - (Game.SprImgGameplayBackground.getHeight() - GAME_SCREEN_HEIGHT)) {
						Game.SprImgGameplayBackground.setPosition(0, yMap
								- PENURUNAN_MAP_HIGH);
					} else {
						yMap = 0 - (Game.SprImgGameplayBackground.getHeight() - GAME_SCREEN_HEIGHT);
					}
					entityBJ.getSprMagicJar().setVisible(false);

				}
				if (mcR.getRctMc().collidesWith(entityBJ.getRctKerdus())) {
					Game.mscSoundKejatuhan.play();
					mcR.setAnim(SPR_ANIME_SAKIT, 1);
					float x = Game.SprIndikatorPoint.getX();
					float y = Game.SprIndikatorPoint.getY();
					if (y <= Game.SprIndikatorGaris.getY() - 8
							+ Game.SprIndikatorGaris.getHeight()) {
						Game.SprIndikatorPoint.setPosition(x, y
								+ PENURUNAN_PIXEL_EASY);
					} else {
						y = Game.SprIndikatorGaris.getY() - 8
								+ Game.SprIndikatorGaris.getHeight();
					}
					float yMap = Game.SprImgGameplayBackground.getY();
					if (yMap >= 0 - (Game.SprImgGameplayBackground.getHeight() - GAME_SCREEN_HEIGHT)) {
						Game.SprImgGameplayBackground.setPosition(0, yMap
								- PENURUNAN_MAP_EASY);
					} else {
						yMap = 0 - (Game.SprImgGameplayBackground.getHeight() - GAME_SCREEN_HEIGHT);
					}
					entityBJ.getSprKerdus().setVisible(false);

				}
				if (mcR.getRctMc().collidesWith(entityBJ.getRctPayung())) {
					Game.mscSoundKejatuhan.play();
					mcR.setAnim(SPR_ANIME_SAKIT, 1);
					float x = Game.SprIndikatorPoint.getX();
					float y = Game.SprIndikatorPoint.getY();
					if (y <= Game.SprIndikatorGaris.getY() - 8
							+ Game.SprIndikatorGaris.getHeight()) {
						Game.SprIndikatorPoint.setPosition(x, y
								+ PENURUNAN_PIXEL_MEDIUM);
					} else {
						y = Game.SprIndikatorGaris.getY() - 8
								+ Game.SprIndikatorGaris.getHeight();
					}
					float yMap = Game.SprImgGameplayBackground.getY();
					if (yMap >= 0 - (Game.SprImgGameplayBackground.getHeight() - GAME_SCREEN_HEIGHT)) {
						Game.SprImgGameplayBackground.setPosition(0, yMap
								- PENURUNAN_MAP_MEDIUM);
					} else {
						yMap = 0 - (Game.SprImgGameplayBackground.getHeight() - GAME_SCREEN_HEIGHT);
					}
					entityBJ.getSprPayung().setVisible(false);

				}
				if (mcR.getRctMc().collidesWith(entityBJ.getRctTas())) {
					Game.mscSoundKejatuhan.play();
					mcR.setAnim(SPR_ANIME_SAKIT, 1);
					float x = Game.SprIndikatorPoint.getX();
					float y = Game.SprIndikatorPoint.getY();
					if (y <= Game.SprIndikatorGaris.getY() - 8
							+ Game.SprIndikatorGaris.getHeight()) {
						Game.SprIndikatorPoint.setPosition(x, y
								+ PENURUNAN_PIXEL_HIGH);
					} else {
						y = Game.SprIndikatorGaris.getY() - 8
								+ Game.SprIndikatorGaris.getHeight();
					}
					float yMap = Game.SprImgGameplayBackground.getY();
					if (yMap >= 0 - (Game.SprImgGameplayBackground.getHeight() - GAME_SCREEN_HEIGHT)) {
						Game.SprImgGameplayBackground.setPosition(0, yMap
								- PENURUNAN_MAP_HIGH);
					} else {
						yMap = 0 - (Game.SprImgGameplayBackground.getHeight() - GAME_SCREEN_HEIGHT);
					}
					entityBJ.getSprTas().setVisible(false);

				}
				/*
				 * if (entityBJ.isOnScreen() && mcR.getCurrentState() ==
				 * MC_STATE_NAIK){ entityBJ.getSprEmber().setVisible(true);
				 * entityBJ.getSprMagicJar().setVisible(true); }
				 */

			case STATE_GAMEPLAY_MENU:
				// Utils.TRACE("Gameplay : onUpdate STATE_GAMEPLAY MENU");
				break;
			case STATE_GAMEPLAY_GAMEOVER:
				// Utils.TRACE("Gameplay : onUpdate STATE_GAMEPLAY GAMEOVER");
				switchState(STATE_GAMEPLAY_GAMEOVER);
				break;
		}

	}

	@Override
	public void reset() {
		// TODO Auto-generated method stub

	}

	private void switchState(int newState) {
		// Utils.TRACE("gameplay : switch State");
		StateCurrent = newState;
		switch (StateCurrent) {
			case STATE_GAMEPLAY_LOADING:

				Scene_Gameplay.attachChild(Game.SprImgLoadingBg);
				Loading.setLoadingType(Loading.LOADING_TYPE_GAMEPLAY);
				break;
			case STATE_GAMEPLAY_INGAME:
				Utils.TRACE("detach loading bg dari scene");

				Scene_Gameplay.detachChild(Game.SprImgLoadingBg);

				// Scene_Gameplay.attachChild(Game.SprImgGameplayBackground);
				Scene_Gameplay.getLastChild().attachChild(Game.SprImgBGUtama);
				Scene_Gameplay.getLastChild().attachChild(Game.SprImgGunung);
				Scene_Gameplay.getLastChild().attachChild(
						Game.SprImgGameplayBackground);
				Game.SprImgGunung
						.setPosition(
								0,
								0 - (Game.SprImgGunung.getHeight() - GAME_SCREEN_HEIGHT));
				Game.SprImgGameplayBackground
						.setPosition(
								0,
								0 - (Game.SprImgGameplayBackground.getHeight() - GAME_SCREEN_HEIGHT));

				// Scene_Gameplay.getLastChild().attachChild(Game.SprPinang);

				Scene_Gameplay.getLastChild().attachChild(
						entityBJ.getSprEmber());
				Scene_Gameplay.getLastChild().attachChild(
						entityBJ.getSprKerdus());
				Scene_Gameplay.getLastChild().attachChild(
						entityBJ.getSprMagicJar());
				Scene_Gameplay.getLastChild().attachChild(
						entityBJ.getSprPayung());
				Scene_Gameplay.getLastChild().attachChild(entityBJ.getSprTas());

				Game.mscBgmGameplay.play();

				time = new Text(Game.SprIndikatorGaris.getX()
						+ TIME_SCORE_POS[0], Game.SprIndikatorGaris.getY()
						- TIME_SCORE_POS[1], font, "00000000000",
						mEngine.getVertexBufferObjectManager());

				HudMainHud = new HUD();
				endHud = new HUD();

				HudMainHud.attachChild(Game.SprBtnRestart);
				HudMainHud.attachChild(Game.SprBtnPanjat);
				HudMainHud.attachChild(Game.SprBtnSwitch);
				HudMainHud.attachChild(Game.SprIndikatorGaris);
				HudMainHud.attachChild(Game.SprIndikatorPoint);
				HudMainHud.attachChild(time);

				mCamera.setHUD(HudMainHud);

				initMc();
				time.setText("0:0");

				Utils.TRACE("Gameplay : switchSTATE STATE_GAMEPLAY INGAME");

				break;
			case STATE_GAMEPLAY_MENU:

				break;
			case STATE_GAMEPLAY_GAMEOVER:

				break;
		}
	}

	private void initMc() {
		// TODO Auto-generated method stub
		if (mcR == null) {
			mcR = new Entity_Mc(Game.AspMainchar, this, MAIN_CHAR_POS[0],
					MAIN_CHAR_POS[1]);
			mcR.setLeftPosX(MAIN_CHAR_POS_SWAP[0]);
			mcR.setRigthPosX(MAIN_CHAR_POS_SWAP[1]);
			Scene_Gameplay.getLastChild().attachChild(Game.AspMainchar);
		}

		txtScore = new Text(0, 0, font, "Score",
				mEngine.getVertexBufferObjectManager());
		txtScore.setPosition(
				(GAME_SCREEN_WIDTH >> 1) - txtScore.getWidth() / 2,
				Utils.getRatioH(280));
		scoreNya = new Text(0, 0, font, "00000",
				mEngine.getVertexBufferObjectManager());
		scoreNya.setPosition(
				(GAME_SCREEN_WIDTH >> 1) - scoreNya.getWidth() / 2,
				txtScore.getY() + txtScore.getHeight() + 10);

		txtHighScore = new Text(0, 0, font, "New High Score",
				mEngine.getVertexBufferObjectManager());
		txtHighScore.setPosition(
				(GAME_SCREEN_WIDTH >> 1) - txtHighScore.getWidth() / 2,
				Utils.getRatioH(280));
		highScore = new Text(0, 0, font, "00000",
				mEngine.getVertexBufferObjectManager());
		highScore.setPosition((GAME_SCREEN_WIDTH >> 1) - highScore.getWidth()
				/ 2, txtHighScore.getY() + txtHighScore.getHeight() + 10);

		txtSubmit = new Text(0, 0, font, "submit",
				mEngine.getVertexBufferObjectManager());

		txtSubmit = new Text(0, 0, fontSubmit, "Submit",
				mEngine.getVertexBufferObjectManager());

		txtSubmit.setPosition((GAME_SCREEN_WIDTH >> 1) - txtSubmit.getWidth()
				/ 2, Utils.getRatioH(415));

		endHud.attachChild(Game.SprSukses);
		endHud.attachChild(Game.SprGagal);
		Game.SprSukses.setVisible(false);

		endHud.attachChild(Game.SprTimer);

		endHud.getLastChild().attachChild(txtScore);
		endHud.getLastChild().attachChild(scoreNya);
		endHud.getLastChild().attachChild(txtHighScore);
		endHud.getLastChild().attachChild(highScore);
		endHud.getLastChild().attachChild(txtSubmit);

		mcR.setVisible(true);

	}

	@Override
	public boolean onSceneTouchEvent(Scene pScene, final TouchEvent event) {
		// TODO Auto-generated method stub

		switch (StateCurrent) {
			case STATE_GAMEPLAY_INGAME:
				if (!CoolDownButton.getSharedInstance().checkValidityNoDelay())
					return false;
				synchronized (this) {

					// TODO Auto-generated method stub

					// button panjat
					if (Utils.isInRect(event.getX(), event.getY(),
							Game.SprBtnPanjat.getX(), Game.SprBtnPanjat.getY(),
							Game.SprBtnPanjat.getWidth(),
							Game.SprBtnPanjat.getHeight())
							&& !mcR.isAnimationRunning()
							&& Game.SprIndikatorPoint.getY() >= Game.SprIndikatorGaris
									.getY()) {

						if (Entity_Mc.CurrentState == MC_STATE_BERDIRI) {
							mcR.setAnim(SPR_ANIME_LOMPAT, 0);
							Entity_Mc.CurrentState = MC_STATE_NAIK;
							counter = true;

						} else {
							if (!mcR.isSwap()) {
								mcR.setAnim(SPR_ANIME_NAIK, 0);
							}
							float x = Game.SprIndikatorPoint.getX();
							float y = Game.SprIndikatorPoint.getY();

							Game.SprIndikatorPoint.setPosition(x, y
									- CHAR_MOVE_SPEED);
							Game.SprImgGameplayBackground.setPosition(0,
									Game.SprImgGameplayBackground.getY()
											+ MAP_MOVE_SPEED);

						}

						if (Game.SprIndikatorPoint.getY() <= Game.SprIndikatorGaris
								.getY()) {
							counter = false;

							Game.mscBgmGameplay.stop();
							Game.mscSoundVictory.play();

							StateCurrent = STATE_GAMEPLAY_GAMEOVER;

							HudMainHud.detachChild(Game.SprBtnRestart);
							endHud.attachChild(Game.SprBtnRestart);

							mCamera.setHUD(endHud);

							Game.SprBtnRestart
									.setPosition(
											(GAME_SCREEN_WIDTH >> 1)
													- Game.SprBtnRestart
															.getWidth() / 2,
											Utils.getRatioH(345));
							cekScore();

							// submitScore();

						}
					}
					// button switch
					else if (Utils.isInRect(event.getX(), event.getY(),
							Game.SprBtnSwitch.getX(), Game.SprBtnSwitch.getY(),
							Game.SprBtnSwitch.getWidth(),
							Game.SprBtnSwitch.getHeight())) {
						Utils.TRACE("cek tombol switch");
						if (Entity_Mc.CurrentState != MC_STATE_BERDIRI) {

							switch (Entity_Mc.CurrentPos) {
								case MC_POS_RIGHT:
									getRctXPos = mcR.getRctX();
									mcR.RctMc.setX(getRctXPos
											+ (Define.GAME_SCREEN_WIDTH / 2));
									mcR.switchPosition(MC_POS_LEFT);
									break;
								case MC_POS_LEFT:
									getRctXPos = mcR.getRctX();
									mcR.RctMc.setX(getRctXPos
											- (Define.GAME_SCREEN_WIDTH / 2));
									mcR.switchPosition(MC_POS_RIGHT);
									Utils.TRACE("pindah1 : gerak dari kiri ke kanan");
									break;
							}
						}
					}
					// button restart
					else if (Utils.isInRect(event.getX(), event.getY(),
							Game.SprBtnRestart.getX(),
							Game.SprBtnRestart.getY(),
							Game.SprBtnRestart.getWidth(),
							Game.SprBtnRestart.getHeight())) {
						Intent restart = new Intent(State_GamePlay.this,
								State_GamePlay.class);
						startActivity(restart);
						finish();
					}

				}
				break;
			case STATE_GAMEPLAY_GAMEOVER:
				if (Utils.isInRect(event.getX(), event.getY(),
						Game.SprBtnRestart.getX(), Game.SprBtnRestart.getY(),
						Game.SprBtnRestart.getWidth(),
						Game.SprBtnRestart.getHeight())) {

					Intent restart = new Intent(State_GamePlay.this,
							State_GamePlay.class);
					startActivity(restart);
					finish();

				} else if (Utils.isInRect(event.getX(), event.getY(),
						txtSubmit.getX(), txtSubmit.getY(),
						txtSubmit.getWidth(), txtSubmit.getHeight())
						&& scoreDb.isHighScore(score)) {

					submitScore();

				}
				break;
		}
		return true;
	}

	private void cekScore() {
		if (scoreDb.isContent()) {
			if (scoreDb.isHighScore(score)) {

				Game.SprSukses.setVisible(true);
				Game.SprGagal.setVisible(false);

				txtHighScore.setVisible(true);
				// highScore.setText(minute + " : " + second);
				// highScore.setText((int) (second / 60) + ":"
				// + (int) (second % 60));
				highScore.setText("  " + String.format("%.02f", score));

				highScore.setVisible(true);

				txtScore.setVisible(false);
				scoreNya.setVisible(false);

				// checkin Heyzab
//				onCheckinClicked(score);

			} else {

				Game.SprGagal.setVisible(true);

				Game.SprBtnRestart.setVisible(true);

				highScore.setVisible(false);
				txtHighScore.setVisible(false);

				txtScore.setVisible(true);
				// scoreNya.setText(minute + " : " + second);
				// scoreNya.setText((int) (second / 60) + ":"
				// + (int) (second % 60));
				scoreNya.setText("  " + String.format("%.02f", score));
				scoreNya.setVisible(true);

				txtSubmit.setVisible(false);
			}

		} else {

			Game.SprSukses.setVisible(true);
			Game.SprGagal.setVisible(false);

			txtHighScore.setVisible(true);
			// highScore.setText(minute + " : " + second);
			// highScore.setText((int) (second / 60) + ":" + (int) (second %
			// 60));
			highScore.setText("  " + String.format("%.02f", score));
			highScore.setVisible(true);

			txtScore.setVisible(false);
			scoreNya.setVisible(false);

			// checkin Heyzab
//			onCheckinClicked(score);

		}

	}

	@Override
	public boolean onKeyDown(final int keyCode, final KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Game.mscBgmGameplay.stop();
			Utils.TRACE("pindah ke menu pake back");
			Intent i = new Intent(State_GamePlay.this, State_MainMenu.class);
			startActivity(i);
			finish();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}

	}

	public void submitScore() {

		this.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				// // TODO Auto-generated method stub

				final AlertDialog.Builder alert = new AlertDialog.Builder(
						context);
				alert.setTitle("Submit Score");
				alert.setMessage("Masukkan Nama");

				final EditText input = new EditText(context);
				input.setInputType(InputType.TYPE_CLASS_TEXT);

				alert.setView(input);

				alert.setPositiveButton("Submit",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub

								mValue = input.getText().toString();
								if (mValue == "") {
									mValue = "Player";
								}

								scoreDb.insertScore(score);
								scoreDb.insertNama(mValue);

								scoreSvc.sendScore(mValue, score);

								Game.mscBgmGameplay.stop();
								Intent score = new Intent(State_GamePlay.this,
										State_Leaderboard.class);
								startActivity(score);
								State_GamePlay.this.finish();
							}
						});
				alert.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub

							}
						});
				final AlertDialog dialog = alert.create();
				dialog.setOnShowListener(new OnShowListener() {

					@Override
					public void onShow(DialogInterface dialog) {
						// TODO Auto-generated method stub
						input.requestFocus();
						final InputMethodManager imm = (InputMethodManager) context
								.getSystemService(context.INPUT_METHOD_SERVICE);
						imm.showSoftInput(input,
								InputMethodManager.SHOW_IMPLICIT);
					}
				});
				dialog.show();

			}
		});

	}

	
	@Override
	protected void onSetContentView() {
	
		final FrameLayout frame = new FrameLayout(this);
		final FrameLayout.LayoutParams frameparams =
				new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
											 FrameLayout.LayoutParams.MATCH_PARENT);
	
		adview = new AdView(this, AdSize.SMART_BANNER, MY_AD);
		adview .refreshDrawableState();
		
		final FrameLayout.LayoutParams adviewparams =
				new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
											 FrameLayout.LayoutParams.WRAP_CONTENT,
											 Gravity.CENTER_HORIZONTAL|Gravity.BOTTOM);
		
		AdRequest adRequest = new AdRequest();
		adview.loadAd(adRequest);
		
		this.mRenderSurfaceView = new RenderSurfaceView(this);
		mRenderSurfaceView.setRenderer(mEngine, this);
		
		frame.addView(mRenderSurfaceView, frameparams);
		frame.addView(adview, adviewparams);
		
		setContentView(frame);
		
		adview.setAdListener(new AdListener() {
			
			public void onReceiveAd(Ad arg0) {
				// TODO Auto-generated method stub
				
			}
			
			public void onPresentScreen(Ad arg0) {
				// TODO Auto-generated method stub
				
			}
			
			public void onLeaveApplication(Ad arg0) {
				// TODO Auto-generated method stub
				//if(Gameplay.curr_game == Gameplay.ON_PLAY){
					//Gameplay.curr_game = Gameplay.ON_PAUSE;
				//}
			}
			
			public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
				// TODO Auto-generated method stub
				
			}
			
			public void onDismissScreen(Ad arg0) {
				// TODO Auto-generated method stub
				
			}
		});
	}


}
